package com.bsoft.exchange.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;


/* 
 * 利用HttpClient进行post请求的工具类 
 */  
public class HttpClientUtil {


    //private  Log logger = LogFactory.getLog(this.getClass());
    public static String doPost(String url,JSONObject jsonObject,String charset)throws IOException {
    	//logger.info("jsonObject:" + jsonObject.toString());
        String result = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            
            httpPost.addHeader("Content-type","application/json; charset=utf-8");  
            httpPost.setHeader("Accept", "application/json"); 
           httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }  
            }
        }finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }

        return result;  
    }
    public static String doGet(String url,String charset) throws IOException {
        String result = null;
        // 创建Httpclient对象
         CloseableHttpClient httpclient = HttpClients.createDefault();
         // 创建http GET请求
         HttpGet httpGet = new HttpGet(url);
         //response 对象
         CloseableHttpResponse response = httpclient.execute(httpGet);
         try {
                 // 执行http get请求
             if(response != null){
                 HttpEntity resEntity = response.getEntity();
                 if(resEntity != null){
                     result = EntityUtils.toString(resEntity,charset);
                 }
             }
             } finally {
                 if (response != null) {
                         response.close();
                     }
                 httpclient.close();
             }
         return result;
    }
}
